<template>
  <div class="loginIndexMain">
    <PageHeader :lang="lang" :isShowAnnouncement = "false"></PageHeader>
      <!--注册页面-->
      <input type="text" name="regPhone" style=" display:none">
      <input type="text" name="regEmail" style=" display:none">
      <input type="password" name="regPassword" style=" display:none">
      <input type="text" name="invitationCode" style=" display:none">
      <div class="login_Main" @keyup.enter="submitRegister" v-show="!isShowSuccessful">
        <router-link to="/user/login" class="no_account" v-html="lang['register yes account number']"></router-link>
        <h3 class="title">{{registerType ? lang['register phone login'] : lang['register email login']}}
          <a @click="toggleRegistType">
            {{registerType ? lang['register email login'] : lang['register phone login']}}
          </a>
        </h3>
        <div class="control-box" v-show="registerType">
          <label>{{lang['register phone number']}}</label>
          <div class="input-wrap phone-wrap">
            <div class="area" :class="{active: isShowAreaList}" @click.stop="areaSelect">{{areaCode ? '+' + areaCode : '+000'}}</div>
           <el-input type="text" name="" :placeholder="lang['register enter Mobile']" v-model="regPhone" ref="regPhone" id="regPhone" oninput="value=value.replace(/[^\d]/g, '')" clearable></el-input>
            <div class="selectAreaList" v-show="isShowAreaList">
              <ul>
                <li v-for="item in countryList" @click="selectList(item)">
                  <span class="number">{{item.Areacode ? '+' + item.Areacode : ''}}</span>
                  <span class="name">{{item.Name}}</span>
                </li>
              </ul>
            </div>
          </div>
        </div>

        <div class="control-box" v-show="!registerType">
          <label>{{lang['register eamil number']}}</label>
          <div class="input-wrap">
             <el-input type="text" name="" :placeholder="lang['register enter email']" v-model="regEmail" ref="regEmail" id ="regEmail" clearable></el-input>
          </div>
        </div>

        <div class="control-box">
          <label>{{lang['register password number']}}</label>
          <div class="input-wrap password-wrap" :class="{active: (passwordType === 'password') && regPassword}">
             <el-input :type="passwordType" name="" :placeholder="lang['register set password']" maxlength="20" v-model="regPassword" ref="regPassword" id="regPassword" clearable></el-input>
             <a class="show_password" @click="showHidePassword" :class="{hide_password: isPassword}" v-show="regPassword"></a>
          </div>
        </div>

        <div class="control-box">
          <label>{{lang['register identifying']}}</label>
          <div class="input-wrap verifyCode-wrap">
            <el-input type="text" name="" :placeholder="lang['register enter identifying']" v-model="regVerifyCode" ref="regVerifyCode" id="regVerifyCode" maxlength="6" clearable></el-input>

            <span class="operation active" v-if="sendMsgDisabled">{{lang['register_ClickGett']}}({{time}})</span>
            <span class="operation" :class="{active: (!regPhone && !regEmail) || !regPassword}" v-if="!sendMsgDisabled" @click="sendVerifyCode">{{lang['register_ClickGet']}}</span>
          </div>
        </div>

        <div class="control-box">
          <label>{{lang['register invitation']}}</label>
          <div class="input-wrap">
            <el-input type="text" name="" :placeholder="lang['register enter Invitation code']" v-model="invitationCode" ref="invitationCode" id="invitationCode"  clearable></el-input>
          </div>
        </div>

        <button type="button" class="buttonBox resgitButtonBox" @click="submitRegister" 
        :class="{disabled: !isDisableBtn || (!regPhone && !regEmail) || !regPassword || regVerifyCode.length < 6}">
          {{lang['register register button']}}
        </button>
         <div class="code_Loge">
            {{lang['register consent agreement']}}
            <router-link class="colorBlue" to="/help/termsOfUse" target = "_blank">{{lang['footUserAgreement']}}</router-link>
         </div>
      </div>

    <div class="errorTip"></div>
    <!-- 弹窗 提示 :isShowBg="false" :isCloseOnClickBg="false"-->
    <SwModal :isShow.sync="isShowSuccessful" modalClass="resgiterSuccess" :onClosed="onClosed" :okText="lang['register set PIN']" :ok="emaileBtndetermine">
      <div class="register_success">
        <img src="./images/register_success.png">
        <h3>{{lang['register Sign Up Success']}}</h3>
        <p>{{lang['register register pinTime']}}</p>
      </div>
    </SwModal>
    <!-- 验证窗口 -->
    <div class="loginVerifySuccess" v-show="isShowVerify">
      <div class="verifyMain">
        <h3>{{lang['login Sliding verification5']}}</h3>
        <img src="./images/closeverify.png"  @click="closeVerify">
        <div id="your-dom-id" class="nc-container"></div>
      </div>
    </div>
    <!-- 验证窗口 -->
  </div>
</template>

<script>
import commonMixins from '@/mixins/common.js'
import Utils from '@/utils/Utils.js'
import ModalApi from '@/components/SwModal/api.js'
import SwModal from '@/components/SwModal'
import { mapActions } from 'vuex'
import CheckInput from '@/utils/CheckInput.js'
import rules from '@/utils/rules.js'
import LoginService from '@/service/LoginService.js'

export default {
  mixins: [commonMixins],
  data () {
    return {
      time: 60,
      sendMsgDisabled: false,
      countryList: [],
      isShowAreaList: false,
      isPassword: false,
      passwordType: 'password',
      regPhone: '',
      regEmail: '',
      regPassword: '',
      areaCode: '',
      regVerifyCode: '',
      countryCode: '',
      registerType: true,
      isDisableBtn: true,
      interval: null,
      isShowSuccessful: false,
      behaviorCode: '',
      isShowVerify: false,
      invitationCode: '',
      nc: null
    }
  },
  watch: {
    langKey () {
      this.initCountryList()
      this.aliyun()
    }
  },
  components: {
    SwModal
  },
  methods: {
    ...mapActions(['saveUserInfo', 'defineLangText']),
    setScrollBar () {
      // 滚动条
      this.$nextTick(() => {
        $('.selectAreaList').niceScroll({
          autohidemode: false
        }).resize()
      })
    },
    toggleRegistType () {
      this.registerType = !this.registerType
      // 每次切换清空验证码发送
      $('.errorTip').hide()
      this.clearMsg()
    },
    reset () {
      this.regPhone = ''
      this.regEmail = ''
      this.regPassword = ''
      this.regVerifyCode = ''
    },
    // 密码是否显示
    showHidePassword () {
      this.isPassword = !this.isPassword
      this.passwordType = (this.passwordType === 'password') ? 'text' : 'password'
    },
    // 显示隐藏地区列表
    areaSelect () {
      this.isShowAreaList = !this.isShowAreaList
    },
    // 地区选择
    selectList (item) {
      this.areaCode = item.Areacode
      this.countryCode = item.Code
      this.isShowAreaList = false
    },
    clearMsg () {
      // 每次切换清空验证码发送
      this.time = 60
      this.sendMsgDisabled = false
      window.clearInterval(this.interval)
    },
    checkNationality () { //  判断是否选择国籍
      if (this.registerType && !this.areaCode) {
        ModalApi.message(this.lang['41005'])
        return false
      } else {
        return true
      }
    },
    // 发送手机/邮箱验证码前调用chackAll
    sendVerifyCode () {
      if ((!this.regPhone && !this.regEmail) || !this.regPassword) {return}
      if (!this.checkNationality()) { return }

      // 检验手机/邮箱、用户名、密码、确认密码、图片验证码是否为空
      this.checkHandle.chackByIdsInOrder([this.registerType ? 'regPhone' : 'regEmail', 'regPassword'])
      .then((info) => {
        let top = $('#' + info.id).offset().top
        let currentInput = $('#' + info.id)
        if (!info.isValid) {
          this.errorTip(top, info.error(), currentInput)
          return
        }

        this.isShowVerify = true
      })
      .catch((info) => {
      })
    },
    // 在注册前检测checkAll和验证码是否为空
    submitRegister () {
      if (!this.isDisableBtn || (!this.regPhone && !this.regEmail) || !this.regPassword || this.regVerifyCode.length < 6) {return}
      if (!this.checkNationality()) { return }

      // 检验手机/邮箱、用户名、密码、确认密码、图片验证码是否为空
      this.checkHandle.chackByIdsInOrder([this.registerType ? 'regPhone' : 'regEmail', 'regPassword', 'regVerifyCode', 'invitationCode'])
      .then((info) => {
        let top = $('#' + info.id).offset().top
        let currentInput = $('#' + info.id)
        if (!info.isValid) {
          this.errorTip(top, info.error(), currentInput)
          return
        }
        this.isDisableBtn = false

        let params = {
          countryCode: this.registerType ? this.countryCode : '',  // 邮箱注册国家编码为空 陈
          areaCode: this.registerType ? this.areaCode : '',
          phoneOrEmail: this.registerType ? this.regPhone : this.regEmail,
          password: this.regPassword,
          verifyCode: this.regVerifyCode,
          verifyDeviceType: this.registerType ? 1 : 2, // 1.手机;2.邮箱
          InvitationCode: this.invitationCode
        }
        this.$http.post('Customer/RegisterUser', params).then((res) => {
          if (res.StatusCode === '200') {
            ModalApi.message(this.lang.register_success, 1000, () => {  // '注册成功'
              LoginService.fakeCheckIn(res.Data)
              // 注册设置完PIN回跳
              this.isShowSuccessful = true

              // this.$router.push({path: '/safety/setPin', query: {from: this.$route.query.from}})
              gtag('event', 'PC注册', {
                'event_category': '注册',
                'event_label': '新用户注册',
                'value': '1'
              })
            })
          } else {
            ModalApi.message(this.lang[res.StatusCode])
          }
          this.isDisableBtn = true
        })
      })
      .catch((info) => {
      })
    },
    initCountryList () {
      this.$http.get('/static/js/data/country_' + this.langKey + '.json', {}, {
        isCustomUrl: true
      }).then((res) => {
        let list = []
        for (let i = 0; i < res.Data.length; i++) {
          for (let j = 0; j < res.Data[i].Data.length; j++) {
            res.Data[i].Data[j].Areacode = res.Data[i].Data[j].Areacode.replace('+', '')
            list.push(res.Data[i].Data[j])
          }
        }
        this.countryList = list
        let index = 0
        let loginPhoneCode = localStorage.getItem('loginPhoneCode')
        if (loginPhoneCode) {
          for (let i = 0; i < this.countryList.length; i++) {
            if (loginPhoneCode === this.countryList[i].Areacode) {
              index = i
            }
          }
          this.areaCode = this.countryList[index].Areacode
          this.countryCode = this.countryList[index].Code
        }

        this.setScrollBar()
      })
    },
    hideLangList () {
      this.isShowAreaList = false
    },
    errorTip (top, error, currentInput) {
      $('.errorTip').stop(true,true).css({'top': top -50}).html(error).fadeIn()
      $(currentInput).parent('.el-input').css({"border": "solid 1px #f00"}) // .parents('.input-wrap')
      setTimeout(function () {
        $('.errorTip').fadeOut()
        $(currentInput).parent('.el-input').css({"border": "solid 1px #4E5A84"}) // .parents('.input-wrap')
      }, 2000)
    },
    registerRules () {
      let onchecked = (result) => {
        let top = $('#' + result.id).offset().top
        let currentInput = $('#' + result.id)
        if (!result.isValid && that._.isFunction(result.error)) {
          this.errorTip(top, result.error(), currentInput)
        }
      }
      let that = this
      this.checkHandle = new CheckInput({
        rules: rules,
        trimValue (val, item) {
          return val.replace(/^\s+|\s+$/, '')
        },
        list: [
          {
            id: 'regPhone',
            input: document.getElementById('regPhone'),
            checkOn: ['blur'],
            onchecked,
            rules: [
              {
                rule: 'required',
                error () {
                  return that.lang['register enter Mobile']
                }
              },
              {
                isReverseRule: true,
                rule (val) {
                  return that.areaCode === '86' && val && !/^1\d{10}$/.test(val)
                },
                error () {
                  return that.lang['please enter the correct phone number']
                }
              },
              {
                rule (val) {
                  let p = Utils.makePromise()
                  that.$http.post('Customer/IsExistPhone', {
                    areaCode: that.areaCode,
                    phone: val,
                    LanguageCode: that.langKey
                  }, {
                    isDisposeCode: false
                  }).then((res) => {
                    if (res.StatusCode === '200') {
                      p.resolveHandle(true)
                    } else {
                      p.rejectHandle(false)
                    }
                  })
                  return p
                },
                error () {
                  if (that.areaCode) {
                    return that.lang['51006'] // 手机已注册
                  } else {
                    return that.lang['41005'] // 选择地区
                  }     
                }
              }
            ]
          },
          {
            id: 'regEmail',
            input: document.getElementById('regEmail'),
            checkOn: ['blur'],
            onchecked,
            rules: [
              {
                rule: 'required',
                error () {
                  return that.lang['register enter email']
                }
              },
              {
                rule: 'email',
                error () {
                  return that.lang['register_EmailErr']
                }
              },
              {
                rule (val) {
                  let p = Utils.makePromise()
                  that.$http.post('Customer/IsExistEmail', {
                    email: val,
                    LanguageCode: that.langKey
                  }, {
                    isDisposeCode: false
                  }).then((res) => {
                    if (res.StatusCode === '200') {
                      p.resolveHandle(true)
                    } else {
                      p.rejectHandle(false)
                    }
                  })
                  return p
                },
                error () {
                  return that.lang['51007']  // 邮箱已注册
                }
              }
            ]
          },
          {
            id: 'regPassword',
            input: document.getElementById('regPassword'),
            checkOn: ['blur'],
            onchecked,
            rules: [
              {
                rule: 'required',
                error () {
                  that.passwordLevel = 0
                  return that.lang['register set password']
                }
              },
              {
                rule (val) {
                  let isValid = true
                  let level = 0
                  let pwd = val
                  let hasLetter = /[a-zA-Z]/.test(pwd) // 拥有字母
                  let hasUpperLetter = /[A-Z]/.test(pwd) // 拥有大写字母
                  let hasLowerLetter = /[a-z]/.test(pwd) // 拥有小写字母
                  let hasNumber = /\d/.test(pwd) // 拥有数字
                  let hasSymbol = /[^a-zA-Z0-9]/.test(pwd) // 拥有字符
                  let minLength = 8 // 最小8位
                  let groups = 0 // 密码强度 0不通过 1弱 2中 3强

                  // 得到组合种类数量
                  groups = [hasLetter, hasNumber, hasSymbol].filter((v) => v === true).length

                  // 至少是8位和拥有两种组合才通过
                  if (pwd.length >= minLength && groups >= 2) {
                    // 有两种组合为弱
                    if (groups >= 2) level = 1
                    // 有两种组合且同时拥有大小写为中
                    if (groups >= 2 && hasUpperLetter && hasLowerLetter) level = 2
                    // 拥有三种组合为中
                    if (groups >= 3) level = 2
                    // 拥有三种组合且同时拥有大小写为强
                    if (groups >= 3 && hasUpperLetter && hasLowerLetter) level = 3
                  } else {
                    isValid = false
                  }

                  that.passwordLevel = level

                  return isValid
                },
                error () {
                  return that.lang['register_formatCorrectPassword']
                }
              }
            ]
          },
          {
            id: 'regVerifyCode',
            input: document.getElementById('regVerifyCode'),
            onchecked,
            rules: [
              {
                rule: 'required',
                error () {
                  return that.lang['register enter identifying']
                }
              }
            ]
          },
          {
            id: 'invitationCode',
            input: document.getElementById('invitationCode'),
            checkOn: ['blur'],
            onchecked,
            rules: [
              {
                rule (val) {
                  let p = Utils.makePromise()
                  that.$http.post('Customer/CustomerCodeExist', {
                    code: val
                  }, {
                    isDisposeCode: false
                  }).then((res) => {
                    if (res.StatusCode === '200') {
                      p.resolveHandle(true)
                    } else {
                      p.rejectHandle(false)
                    }
                  })
                  if (!val) {p.resolveHandle(true)}
                  return p
                },
                error () {
                  // console.log(1)
                  return that.lang['48001']
                }
              }
            ]
          },
        ]
      })
      // document.getElementById('regPhone').onkeypress = function (e) {
      //   if (e.keyCode < 48 || e.keyCode > 57) {
      //     e.returnValue = false
      //   }
      // }
    },
    closeVerify () {
      this.isShowVerify = false
      this.aliyun()
    },
    aliyun () {
      let self = this
      // ar_SA:阿拉伯文
      // de_DE:德文
      // es_ES:西班牙文
      // fr_FR:法文
      // in_ID:印尼语
      // it_IT:意大利文
      // iw_HE:希伯来语
      // ja_JP:日文
      // ko_KR:韓文
      // nl_NL:荷蘭文
      // pt_BR:波蘭文
      // ru_RU:俄文
      // th_TH:泰文
      // tr_TR:土耳其文
      // vi_VN:越南文
      // cn:简体中文
      // tw:繁体中文
      // en:英文
      let key = ''
      if (self.langKey === 'zh-CN') { key = 'cn'}
      if (self.langKey === 'en') { key = 'en'}
      if (self.langKey === 'zh-Hant') { key = 'tw'}
      if (self.langKey === 'fr') { key = 'fr_FR'}
      if (self.langKey === 'ja') { key = 'ja_JP'}
      if (self.langKey === 'ko') { key = 'ko_KR'}
      if (self.langKey === 'nl') { key = 'nl_NL'}
      if (self.langKey === 'vi') { key = 'vi_VN'}

      let ncToken = ['FFFF0N0000000000635A', (new Date()).getTime(), Math.random()].join(':')
      let ncOpt = {
        renderTo: '#your-dom-id',
        appkey: 'FFFF0N0000000000635A',
        scene: 'nc_login',
        token: ncToken,
        customWidth: '100%',
        trans: { 'key1': 'code0' },
        elementID: ['usernameID'],
        is_Opt: 0,
        language: key,
        isEnabled: true,
        timeout: 3000,
        times: 5,
        apimap: {
        },
        callback (data) {
          self.pcTest(data)
        }
      }
      this.nc = new noCaptcha(ncOpt)
      this.nc.upLang(key, {
        _startTEXT: self.lang['login Sliding verification'], // '请按住滑块，拖动到最右边',
        _yesTEXT: self.lang['login Sliding verification2'], // '验证通过',
        _error300: self.lang['login Sliding verification3'], // '哎呀，出错了，点击<a href=\'javascript:__nc.reset()\'>刷新</a>再来一次',
        _errorNetwork: self.lang['login Sliding verification4'], // '网络不给力，请<a href=\'javascript:__nc.reset()\'>点击刷新</a>',
      })
      self.nc.reset()
    },
    pcTest (data) {
      this.$http.post('Aliyun/PCSlider', {
        csessionid: data.csessionid,
        sig: data.sig,
        token: data.token,
        value: data.value,
        BusinessType: 2 // 0 未知类型， 1 登录， 2注册， 3 找回密码
      }).then((res) => {
        if (res.StatusCode === '200') {
          res.Data = res.Data || {}
          this.behaviorCode = res.Data.BehaviorCode || ''
          this.closeVerify()
          // 发送验证码
          this.$http.post('Customer/SendVerifyCode', {
            verifyDeviceType: this.registerType ? 1 : 2, // 1.手机;2.邮箱
            clientType: 0, // 0,网页;1,android;2,iOS
            businessType: 1, // 1注册发验证码；2找回密码发验证码
            areaCode: this.registerType ? this.areaCode : '',
            phoneOrEmail: this.registerType ? this.regPhone : this.regEmail,
            Code: this.behaviorCode
          }, {
            isDisposeCode: false
          })
          .then((res) => {
            if (res.StatusCode === '200') {
              ModalApi.message(this.lang['VerificationCodeSuccessful']) // '发送验证码成功'
              // 倒计时
              window.clearInterval(this.interval)
              let self = this
              self.sendMsgDisabled = true
              this.interval = window.setInterval(function () {
                if ((self.time--) <= 0) {
                  self.time = 60
                  self.sendMsgDisabled = false
                  window.clearInterval(self.interval)
                }
              }, 1000)
              // 倒计时
            } else {
              ModalApi.message(this.lang[res.StatusCode])
            }
          })
          // 发送验证码
        }
      })
    },
    onClosed () {

    },
    emaileBtndetermine () {
      this.isShowSuccessful = false
      this.$router.push({path: '/safety/setPin', query: {from: this.$route.query.from}})
    }
  },
  mounted () {
    this.initCountryList()
    document.addEventListener('click', this.hideLangList)
    this.registerRules()
    this.aliyun()
  },
  beforeDestroy () {
    document.removeEventListener('click', this.hideLangList)
    window.clearInterval(this.interval)
  }
}
</script>

<style lang="less">
  .nicescroll-cursors {
    border: none !important;
    background-color: #454e7d !important;
  }
  .modal.resgiterSuccess {
    padding-bottom: 80px;
    width: 568px;
    background-color: #112135 !important;
    box-shadow: 0 2px 4px 0 rgba(0,0,0,0.37);
    border-radius: 10px;
    z-index: 1000;
    .register_success {
      padding: 0 16px;

      img{
        display: block;
        margin: 66px auto 30px;
      }

      h3 {
        line-height: 30px;
        color: #fff;
        text-align: center;
        font-size: 24px;
      }
      p {
        padding: 40px 16px 50px;
        color: #fff;
        font-size: 18px;
        text-align: center;
        line-height: 24px;
      }
    }

    .btn.ok {
      font-size: 18px;
    }
  }

</style>
